package org.qpcr.community.auth.service;

import org.hswebframework.web.crud.query.QueryHelper;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.hswebframework.web.system.authorization.api.entity.UserEntity;
import org.qpcr.community.auth.entity.UserDetail;
import org.qpcr.community.auth.entity.UserDetailEntity;
import org.qpcr.community.auth.enums.DefaultUserEntityType;
import org.qpcr.community.auth.enums.UserEntityTypes;
import org.qpcr.community.io.file.FileManager;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;


/**
 * 用户详情管理
 * <p>
 * 通过通用增删改查接口实现用户详情增删改查功能.
 * 通过用户id获取用户基本信息（包含租户成员信息）
 *
 * @author zhouhao
 * @see org.hswebframework.web.crud.service.GenericReactiveCacheSupportCrudService
 * @since 1.3
 */
@Service
public class UserDetailExtService extends GenericReactiveCrudService<UserDetailEntity, String> {

    private final QueryHelper queryHelper;


    public UserDetailExtService(
                                QueryHelper queryHelper,
                                FileManager fileManager,
                                WebClient.Builder builder) {
        this.queryHelper = queryHelper;
        // 注册默认用户类型
        UserEntityTypes.register(Arrays.asList(DefaultUserEntityType.values()));

    }



    /**
     * 根据code查询用户信息
     *
     * @param code
     * @return Flux<UserDetail>
     */
    public Mono<UserEntity> findUserByCode(String code) {
        String sql = " select d.id,s.status," +
            "d.name," +
            "s.username," +
            "s.password," +
            "s.salt," +
            "d.org_id as orgId," +
            "d.unit_id as unitId," +
            "d.telephone," +
            "d.role_type roleType," +
            "d.create_time createTime," +
            "d.modify_time modifyTime," +
            "d.delete_type deleteType " +
            " from s_user s left join s_user_detail d on d.id=s.id where d.code='" + code + "'";
        return queryHelper.select(sql,UserEntity::new).fetch().collectList().map(
            entity->
                entity.get(0)
        );
//        return queryHelper.select(sql,UserEntity::new).fetchPaged(1,1).cast(UserEntity.class);
    }







}
